package com.lucy.nepu.module.raward.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import com.lucy.common.anno.FormLock;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.nepu.loader.PeriodLoader;
import com.lucy.nepu.module.raward.entity.RAward;
import com.lucy.nepu.module.raward.lib.RAwardDict;
import com.lucy.nepu.module.raward.lib.RAwardDictService;
import com.lucy.nepu.module.raward.params.RAwardCreateParams;
import com.lucy.nepu.module.raward.params.RAwardQueryParams;
import com.lucy.nepu.module.raward.params.RAwardUpdateParams;
import com.lucy.nepu.module.raward.service.RAwardService;
import com.lucy.nepu.module.tmaterial.lib.TMaterialDict;
import com.lucy.nepu.module.topic.model.ExtParams;
import com.lucy.nepu.utils.ValidUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.Random;

@RestController
@RequestMapping("nepu")
@Api(tags = "科研获奖")
public class RAwardController {
    @Autowired
    RAwardService service;

    @Autowired
    RAwardDictService dictService;

    @Autowired
    PeriodLoader periodLoader;


//    @PostMapping("awards/storage")
//    @FormLock(lockKey = "AWARD_STORE",needLogin = true)
//    @ApiOperation(value = "暂存记录",notes = "")
//    public ResponseDTO<Object> setStorage(@RequestBody NepuAwardAddDTO dto){
//        Long userId = StpUtil.getLoginIdAsLong();
//        Optional<Object> dictOp = dictServiceCtl.getById(dto.getAwardDictId(),ResearchTypeConst.AWARD);
//        if (!dictOp.isPresent()){
//            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//        }
//        NepuAwardDict dict = (NepuAwardDict) dictOp.get();
//        String awardType = dict.getAwardType();
//        NepuDraft draft = new NepuDraft();
//        draft.setFormId(ResearchTypeConst.AWARD+awardType);
//        draft.setStatus(1);
//        draft.setUserId(userId);
//        draft.setFormJsonStr(JsonUtil.obj2String(dto));
//        return ResponseDTO.succData(draftService.saveOne(draft));
//    }
//
//    @GetMapping("awards/storage")
//    @ApiOperation(value = "获取最新暂存")
//    public ResponseDTO<Object> getStorage(@RequestParam("awardType") String awardType){
//        //log.info(awardType);
//        Long userId = StpUtil.getLoginIdAsLong();
//        Optional<NepuDraft> draftOp = draftService.getLastDraft(userId,ResearchTypeConst.AWARD+awardType);
//        if (!draftOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//        NepuDraft draft = draftOp.get();
//        return ResponseDTO.succData(JsonUtil.string2Obj(draft.getFormJsonStr(),NepuAwardAddDTO.class));
//    }
//
//    @GetMapping("awards/storage/all")
//    @ApiOperation(value = "获取全部暂存")
//    public ResponseDTO<Object> getAllStorage(@RequestParam("awardType") String awardType){
//        Long userId = StpUtil.getLoginIdAsLong();
//        List<NepuDraft> drafts = draftService.getFormAllDrafts(userId,ResearchTypeConst.AWARD+awardType);
//        return ResponseDTO.succData(drafts);
//    }


    @PostMapping("rawards")
    @FormLock(lockKey = "AWARD_FORM",needLogin = true)
    @ApiOperation(value = "新建记录",notes = "")
    public ResponseDTO<Object> saveOne(@RequestBody @Validated RAwardCreateParams params){
        // 1. 获取操作人员ID
        String operator = StpUtil.getLoginIdAsString();
        //查询是否存在被驳回的重复提交
        String errMsg = ValidUtil.formValid(params);
        if (!Validator.isEmpty(errMsg)){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,errMsg);
        }
        String periodId = periodLoader.getPeriodId();
        // 3. 获取词典信息
        RAwardDict dict = dictService.getOneUnwrap(params.getAwardDictId());
        // 4. 写入记录 并赋值最大工作量
        RAward award = new RAward();
        BeanUtil.copyProperties(params,award, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        award.setWorkload(dict.getWorkloadMax());
        award.setPeriodId(periodId);
        award.setStatus(1);
        ExtParams extParams = new ExtParams();
        extParams.setDeptId(params.getDeptId());
        extParams.setDeptName(params.getDeptName());
        award.setExtParams(extParams);
        RAward saveRes=service.saveOne(award);
        // 5. 写入绑定文件信息 -- 修改为异步任务
        List<String> fileIds = params.getFileIds();

        return ResponseDTO.succData(saveRes);
    }





    @DeleteMapping("rawards/{id}")
    @ApiOperation(value = "删除单条记录",notes = "传入ID")
    public ResponseDTO<Object> deleteOne(@PathVariable("id") String id){
        service.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }

    @GetMapping("rawards/{id}")
    @ApiOperation(value = "查询单条记录",notes = "传入ID")
    public ResponseDTO<RAward> getOne(@PathVariable("id") String id){
        Optional<RAward> entityOp = service.getOne(id);
        return entityOp.map(ResponseDTO::succData).orElseGet(() -> ResponseDTO.wrap(HttpStatus.NOT_FOUND));
    }


    /** 更新单条记录 **/
    @PutMapping("rawards")
    @ApiOperation(value = "更新单条记录",notes = "")
    public ResponseDTO<Object> updateOne(@RequestBody @Validated RAwardUpdateParams params){
        Optional<RAward> awardOp = service.getOne(params.getId());
        if (!awardOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND);
        }
        RAward award = awardOp.get();
        BeanUtil.copyProperties(params,award,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return ResponseDTO.succData(service.updateOne(award));
    }

//    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
//    @PutMapping("awards/files")
//    @ApiOperation(value = "更新附件信息",notes = "")
//    public ResponseDTO<Object> updateFiles(@RequestBody @Validated FileUpdateDTO dto){
//        Long userId = StpUtil.getLoginIdAsLong();
//        Optional<Object> awardOp = researchServiceCtl.getById(dto.getMapperId(),ResearchTypeConst.AWARD);
//        if (!awardOp.isPresent()){
//            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//        }
//        NepuAward award = (NepuAward) awardOp.get();
//        if (!userId.equals(award.getLeaderId())){
//            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"非负责人无法修改");
//        }
//        // 清理之前的附件信息
//        nepuResearchFileService.deleteEntityLink(award.getId());
//        // 写入新的附件信息
//        List<String> fileIds = dto.getFileIds();
//        nepuResearchFileService.batchBindFile(ResearchTypeConst.AWARD,award.getId(),fileIds);
//        // 返回操作信息
//        return ResponseDTO.succMsg("更新成功");
//    }


    @GetMapping("rawards")
    @ApiOperation(value = "查询全部",notes = "")
    public ResponseDTO<Object> getAll(RAwardQueryParams params){
        Sort sort;
        if(params.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC,params.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, params.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(params.getPageNum() - 1 , params.getPageSize(), sort);

        RAward award = new RAward();
        BeanUtil.copyProperties(params,award, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<RAward> example = Example.of(award);
        return ResponseDTO.succData(service.getAll(pageable,example));
    }

    @PutMapping("rawards/{id}/workload")
    @ApiOperation(value = "修改记录工作量")
    public ResponseDTO<Object> updateWorkload(@PathVariable("id") String id,@RequestParam("workload") Double workload){
        Optional<RAward> entityOp = service.getOne(id);
        if (!entityOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"未找到对应课题记录");
        }
        RAward award = entityOp.get();
        String dictId = award.getAwardDictId();
        Optional<RAwardDict> dictOp = dictService.getOne(dictId);
        if (!dictOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"未找到课题关联词典记录");
        }
        RAwardDict dict = dictOp.get();
        if (workload > dict.getWorkloadMax() || workload < dict.getWorkloadMin()){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,"工作量范围错误");
        }
        award.setWorkload(workload);
        // 写入记录
        return ResponseDTO.succData(service.updateOne(award));
    }
}
